package org.zls.client;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.widgets.grid.ColumnModel;

public class ColumnToggle extends DialogBox implements ClickListener {

	private FlexTable table;
	private ResultTable grid;
	private ColumnModel model;
	private final static int NUM_COLS = 4;

	public ColumnToggle(ResultTable grid, ColumnModel model) {

		this.grid = grid;
		this.model = model;
		
		setText("Select columns");

		table = new FlexTable();

		Button OKButton = new Button("OK", this);

		DockPanel dock = new DockPanel();
		dock.setSpacing(4);
		dock.add(OKButton, DockPanel.SOUTH);
		dock.add(table, DockPanel.CENTER);

		dock.setCellHorizontalAlignment(OKButton, DockPanel.ALIGN_CENTER);
		dock.setWidth("100%");
		setWidget(dock);
	}

	public void onClick(Widget sender) {
		for (int i = 1; i < grid.getColumnModel().getColumnCount(); i++) {
			
			int row = (i - 1) / NUM_COLS;
			int col = (i - 1) % NUM_COLS;
			
			CheckBox currBox = (CheckBox) table.getWidget(row, col);
			model.setHidden(i, !currBox.isChecked());
		}
		hide();
		grid.reconfigure(grid.getStore(), model);
	}
	
	public void onShow(ColumnModel model) {
		for (int i = 1; i < grid.getColumnModel().getColumnCount(); i++) {
			
			int row = (i - 1) / NUM_COLS;
			int col = (i - 1) % NUM_COLS;
			
			CheckBox box = new CheckBox(model.getColumnHeader(i));
			
			table.setWidget(row, col, box);
			
			((CheckBox) table.getWidget(row, col))
					.setChecked(!model.isHidden(i));
		}
	}
}